package bzapps.weynak;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import bzapps.weynak.MyOverlay.OnSaveMyPosition;
import bzapps.weynak.ar.com.jwetherell.augmented_reality.activity.Demo;
import bzapps.weynak.fb.SessionStore;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.google.android.c2dm.C2DMessaging;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Maps extends MapActivity 
{
	private MapView map;
	private MapController mapController;
	public LocationManager locationManager;
	public LocationListener locationListener;
	
	public ArrayList<Friend> friends;
	public ArrayList<Note> notes;
	public ArrayList<Photo> photos;
	public ArrayList<Note> mynotes;
	public ArrayList<Photo> myphotos;
	
	static MyOverlay myLocation;
	FriendOverlay facebook;
	List<Overlay> mapOverlays;
	
	Button actions, saveLocation, takePhoto, share, layers, views;
	LinearLayout actionbar;
	TextView txtview_username;
	ImageView userimg;
	String firstname,lastname, action , username, picture_link, client_id;
	double lon,lat, lonc, latc;
	ProgressDialog pd;
	
	int isVisible = 0;
	int location_size = 0;
	public static boolean batterywarning;
		
	public String file_path;
	public String snap_name;
	
	Uri outputFileUri;
	
	static final int INIT_LOADING = -1;
	static final int PHOTO_TAKEN = 0 ;
	static final int PHOTO_SAVED = 1;
	static final int LOCATION_SAVED = 2;
	static final int LOCATIONS_DONE = 3;
	static final int LOCATIONS_EMPTY = 4;
	static final int PROFILE_PIC = 5;
	static final int BATTERY_LOW = 6;
	static final int LOGOUT = 7;
	static final int PHOTO_UPLOADED = 8;
	static final int LOCATION_PUBLISHED = 9;
	static final int TAKE_PICTURE = 10;
	static final int NOTES_DONE = 11;
	static final int PHOTOS_DONE = 12;
	static final int MY_NOTES_DONE = 13;
	static final int MY_PHOTOS_DONE = 14;
	static final int SETTINGS = 100;
	static final int UID = 10001;
	
	private int loadstatus = -2;
	private SharedPreferences pref;

	public static final String URI_LINK = "http://www.bz-apps.com/weynak";
	public static final String USER_DATA = "/authent.php?log_in=get_credentials";
	public static final String senderID = "christophe.zoghbi@gmail.com";
	
	protected CharSequence[] _options = { "My friends' locations", "My saved locations", "My friends' saved locations", "My photos", "My friends' photos" };
	protected boolean[] _selections =  new boolean[ _options.length ];
	
	WakeLock lock;
    public static Handler lochandler;
    public static Handler utils;
    
    static final String APP_ID = "119791898115838";
	private Facebook mFacebook;
    final ProgressDialog dialog = null; ;
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.maps);
    
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    batterywarning = false;
    
    sendBroadcast(new Intent("weynak.UPDATE_BATTERY"));
    sendBroadcast(new Intent("weynak.UPDATE_LOCATION"));
    
    client_id = pref.getString("uid", "Client ID not found");
    
    for(int i=0; i<_options.length; i++)
    {
        _selections[i] = pref.getBoolean((String) _options[i],true);   
    }
    initHandler();
    initMap();
    initOverlays();
    
    if(checkInternetConnection()){
    try {
		loadUserData(client_id);
	} catch (Exception e){
		Log.e("WEYNAK.load.user.data", e.getMessage());
		}
    }
    else Toast.makeText(this, "Please check your internet connectivity", 10).show();
    
	NotificationManager m = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    m.cancel(Maps.UID);
	
    actions = (Button)findViewById(R.id.map_actions);
    userimg = (ImageView)findViewById(R.id.map_userpic);
    txtview_username = (TextView)findViewById(R.id.map_coord);
    saveLocation = (Button)findViewById(R.id.mapsaction_saveloc);
    share = (Button)findViewById(R.id.mapsaction_share);
    takePhoto = (Button)findViewById(R.id.mapsaction_photo);
    views = (Button) findViewById(R.id.mapsaction_layers);
    layers = (Button)findViewById(R.id.mapsaction_layers2);
    actionbar = (LinearLayout)findViewById(R.id.map_actionbar);
    actions.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			if(isVisible==0){
			actionbar.setVisibility(View.VISIBLE);
			isVisible = 1;
		}  
			else {
				actionbar.setVisibility(View.GONE);
				isVisible = 0;
			}
		}
	});
    takePhoto.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			createFolder();			
		}
	});
    saveLocation.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			
			 final Dialog mydialog = new Dialog(Maps.this);
			 mydialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			 mydialog.setContentView(R.layout.savelocation_layout);
			 final EditText name = (EditText)mydialog.findViewById(R.id.saveloc_edtxt_name);
			 final EditText note = (EditText)mydialog.findViewById(R.id.saveloc_edtxt_note);
			 Button ok = (Button)mydialog.findViewById(R.id.saveloc_ok);
			 Button cancel = (Button)mydialog.findViewById(R.id.saveloc_cancel);
			 ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(!name.getText().toString().equals("") && !note.getText().toString().equals("")) 
					{
						Location l = myLocation.getLastFix();
						saveNote(l, name.getText().toString(), note.getText().toString());
						mydialog.dismiss();
					}
					else Toast.makeText(getBaseContext(), "Please insert all fields", 10).show();	
				}
			});
			 cancel.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					mydialog.dismiss();
					
				}
			});
			 
			mydialog.show();
		
		}
	});
  
    share.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Maps.this)
            .setTitle("Share your location")
            .setMessage("Would you like to publish your current location on Facebook?")
            .setIcon(R.drawable.weynak_icon)
           .setPositiveButton("Ok", new Dialog.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                	PublishOnWall();
                	dialogInterface.dismiss();
                }
            })
            .setNegativeButton("Cancel", new Dialog.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                   dialog.dismiss();
                }

            });
    builder.create().show();
		
		}
	});
    
    views.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			final CharSequence[] choice = {"Satellite","Terrain","Live Camera"};

	         
	          AlertDialog.Builder alert = new AlertDialog.Builder(Maps.this);
	          alert.setTitle("Choose a view");
	          alert.setSingleChoiceItems(choice,-1,

	             new DialogInterface.OnClickListener()
	          {
	              @Override
	              public void onClick(DialogInterface dialog, int which) 
	              {
	                 
	            	  if (choice[which]=="Satellite")
	                  {
		                	 map.setTraffic(false);
		                     map.setSatellite(true);
		                     map.setStreetView(false);
		                     dialog.dismiss();
		               }
	                  else if (choice[which]=="Terrain")
	                  {
		                	 map.setTraffic(false);
		                     map.setSatellite(false);
		                     map.setStreetView(true);
		                     dialog.dismiss();
		               }
	                  else if (choice[which]=="Live Camera")
	                  {
		                	dialog.dismiss();
		                	startActivity(new Intent(Maps.this, Demo.class));
		               }
	              }
	          });
	          
	          alert.show();
		}
	});   
    
    layers.setOnClickListener(new OnClickListener() {
    	
    	
			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder layers = new AlertDialog.Builder(Maps.this);
				layers.setTitle( "Choose your layers" )
	        	.setMultiChoiceItems( _options, _selections, new OnMultiChoiceClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int clicked, boolean selected) {
						pref.edit().putBoolean(_options[clicked].toString() , selected).commit();
					}
				});
				layers.setPositiveButton( "OK", new DialogButtonClickHandler()).create();
				layers.setNegativeButton("Clear map", new DialogButtonClickHandler()).create();
				layers.setCancelable(false);
				layers.show();
			}
		});
    
  }
  public class DialogButtonClickHandler implements DialogInterface.OnClickListener
	{
		public void onClick( DialogInterface dialog, int clicked )
		{
			switch( clicked )
			{
				case DialogInterface.BUTTON_POSITIVE:
					  mapOverlays = map.getOverlays();
					  mapOverlays.clear();
					  initOverlays();
					  break;
				case DialogInterface.BUTTON_NEGATIVE:
					mapOverlays = map.getOverlays();
					mapOverlays.clear();
					break;
			}
		}
	}
  
  public void createFolder(){
		
		String dirName = "/sdcard/Weynak"; 
	    File newFile = new File(dirName); 
	    newFile.mkdirs(); 
	    try{
		    if(newFile.exists()){ 
		    	 savePhoto();
		    }
		    else { 
			    createFolder();
		    } 
		} 
		   catch(Exception e){  
			} 
	}
	public void savePhoto() throws IOException{
		
		Calendar cal = Calendar.getInstance();
	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
	 	String curdate =  sdf.format(cal.getTime());
	 	String client = pref.getString("uid", "UnkownClient");
	 	snap_name = client +"_"+ curdate;
		    	File f = new File(Environment.getExternalStorageDirectory()
              + File.separator + "Weynak"+ File.separator + snap_name + ".jpg");
		file_path = f.toString();
    	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		outputFileUri = Uri.fromFile(f);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PICTURE);
		
      	
      		
}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	     switch (requestCode) {
	        case SETTINGS:
	        
	            if (pref.getBoolean("privacycheck", false)) {
	                try {
	                    Toast.makeText(this, "Updating ... ", Toast.LENGTH_LONG).show();
	                } catch (Exception e) {
	                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
	                }
	            }
	            
	            break;
	        case TAKE_PICTURE:
	        	  if (resultCode == Activity.RESULT_OK) {
	        		   
	        		    if (data == null) {
	        		  	  new Thread() {

	        				  public void run() {
	        					  if(checkInternetConnection()){
	        						uploadfile up = new uploadfile();
	        						utils.sendEmptyMessage(PHOTO_TAKEN);
	    	        		  		up.doFileUpload(file_path);
	        					  }
	        					  else Toast.makeText(getBaseContext(), "Please check your internet connection", 10).show();
	        				  		}

	        				  }.start();
	        		    }
	        		  }
	        	break;
	        default:
	            break;
	        }
	
	}
	
	public void PublishOnWall(){
		if(checkInternetConnection()){
		try {
    		mFacebook = new Facebook(APP_ID);
    	   	new AsyncFacebookRunner(mFacebook);
    	    SessionStore.restore(mFacebook, Maps.this);
    		if (mFacebook.isSessionValid()) {
    		    Bundle parameters = new Bundle();
    		    String address = WeynakUtils.getAddress(Maps.this, myLocation.getLastFix());
    		    parameters.putString("message", "Hey I'm at " + address);
    		    try {
    				mFacebook.request("me/feed", parameters,"POST");
    				utils.sendEmptyMessage(LOCATION_PUBLISHED);
    			} catch (IOException e) {
    			}
    		}
    	} catch(Exception e){
			Log.e("WEYNAK.publish.location", e.getMessage());
		}
	}
		else Toast.makeText(getBaseContext(), "Please check your internet connection", 10).show();
}
	
	public boolean checkInternetConnection() {
	        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	        // test for connection
	        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable()
	                && cm.getActiveNetworkInfo().isConnected()) {
	            return true;
	        } else {
	            Log.v("WEYNAK.internet.check", "No Internet Connection");
	            return false;
	        }
	    }
	
  private void initHandler()
  {

      lochandler = new Handler() {

          @Override
          public void handleMessage(Message msg)
          {
              getWindow().setFeatureInt(Window.FEATURE_PROGRESS, msg.what);

              switch (msg.what) {
              case 25:
            	  pd = ProgressDialog.show(Maps.this, "", "Refreshing locations... ",true,true);
            	  break;
              case LOCATIONS_EMPTY:
            	  pd.dismiss();
            	  break;
             
              }
          }
      };
  
  	utils = new Handler(){
		 @Override
       public void handleMessage(Message msg)
         {
			 switch (msg.what) {
			 case PHOTO_TAKEN:
				 Toast.makeText(getBaseContext(), "Uploading Photo ...", 10).show();
				 break;
			 case PHOTO_SAVED:
				 Toast.makeText(getBaseContext(), "Picture was successfully saved! ", 10).show();
				 break;
			 case PHOTO_UPLOADED:
				 uploadfile up = new uploadfile();
				 up.insertDBPhoto(snap_name,client_id,myLocation.getLastFix());
				 break;
			 case LOCATION_SAVED:
				 Toast.makeText(getBaseContext(), "Location was successfully saved!", 10).show();
				 break;
			 case PROFILE_PIC:
				 txtview_username.setText(username);
		         Bitmap img = WeynakUtils.getImageBitmap(picture_link);
			     userimg.setImageBitmap(img);
			     if(!pref.getBoolean("isPushRegistered", false))
			     {
			    	 C2DMessaging.register(getBaseContext(), senderID);
			     }
			    
				 break;
			 case LOCATION_PUBLISHED:
				 Toast.makeText(getBaseContext(), "Your location was published on your wall!", 10).show();
			case BATTERY_LOW:
		          final Dialog warning = new Dialog(Maps.this);
		          warning.requestWindowFeature(Window.FEATURE_NO_TITLE);
		          warning.setContentView(R.layout.batterywarning);
		          Button exit = (Button)warning.findViewById(R.id.battwarning_exit);
		          Button con = (Button)warning.findViewById(R.id.battwarning_continue);
		          exit.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Maps.this.finish();
						Maps.this.stopService(new Intent(getBaseContext(), UpdateLocationService.class));
					}
				});
		          con.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						WindowManager.LayoutParams lp = getWindow().getAttributes();
						lp.screenBrightness = 25 / 100.0f;
						getWindow().setAttributes(lp);
						android.provider.Settings.System.putInt(getContentResolver(),android.provider.Settings.System.SCREEN_BRIGHTNESS, 25);
						warning.dismiss();
					}
				});
		          
		      	warning.setCancelable(false);
		      	warning.show();
				 break;
			case LOGOUT:
				finish();
				break;
			 }
         }
	};
  }
  	     
  private void displayFriends(){
	  String lastupdated;
	  for(int i=0; i<friends.size(); i++)
	  {
			Friend f = new Friend(); 
			f = friends.get(i);
			lat = f.lat;
			lon = f.lon;
			firstname = f.first_name;
			lastname = f.last_name;
			lastupdated = f.date;
			String userpic = f.picture;
			LocatePosition(lon, lat, firstname+ " " + lastname , userpic, lastupdated);
      }
  }
  
  private void displayMyNotes(){
	  String mynotes_fn,mynotes_ln,mynotes_date,mynotes_desc,mynotes_title;
	  double mynotes_lat,mynotes_lon;
	  for(int i=0; i<mynotes.size(); i++){
			Note n = new Note(); 
			n = mynotes.get(i);
			mynotes_lat = n.lat;
			mynotes_lon = n.lon;
			mynotes_fn = n.fname;
			mynotes_ln = n.lname;
			mynotes_date = n.date;
			mynotes_desc = n.desc;
			mynotes_title = n.title;
			LocateNote(mynotes_lon, mynotes_lat, mynotes_title, mynotes_desc, mynotes_date,mynotes_fn + " " + mynotes_ln);
	  }
  }
  
  private void displayNotes(){
   	  String notes_fn,notes_ln,notes_date,notes_desc,notes_title;
	  double notes_lat,notes_lon;
	  for(int i=0; i<notes.size(); i++){
			Note n = new Note(); 
			n = notes.get(i);
			notes_lat = n.lat;
			notes_lon = n.lon;
			notes_fn = n.fname;
			notes_ln = n.lname;
			notes_date = n.date;
			notes_desc = n.desc;
			notes_title = n.title;
			LocateNote(notes_lon, notes_lat, notes_title, notes_desc, notes_date,notes_fn + " " + notes_ln);
	  }
  }
  
  private void displayMyPhotos(){
  	  String myphotos_fn,myphotos_ln,myphotos_date,myphotos_snap;
	  double myphotos_lat,myphotos_lon;
	  for(int i=0; i<myphotos.size(); i++){
			Photo n = new Photo(); 
			n = myphotos.get(i);
			myphotos_lat = n.lat;
			myphotos_lon = n.lon;
			myphotos_fn = n.fname;
			myphotos_ln = n.lname;
			myphotos_date = n.date;
			myphotos_snap = n.snapshot;
			LocatePhoto(myphotos_lon, myphotos_lat, myphotos_fn + " " + myphotos_ln, myphotos_date, myphotos_snap);
	  }
  }
  
  private void displayPhotos(){
 	  String photos_fn,photos_ln,photos_date,photos_snap;
	  double photos_lat,photos_lon;
	  for(int i=0; i<photos.size(); i++){
			Photo n = new Photo(); 
			n = photos.get(i);
			photos_lat = n.lat;
			photos_lon = n.lon;
			photos_fn = n.fname;
			photos_ln = n.lname;
			photos_date = n.date;
			photos_snap = n.snapshot;
			LocatePhoto(photos_lon, photos_lat, photos_fn + " " + photos_ln, photos_date, photos_snap);
	  }
  }
  
  private void initMap()
  {
      map = (MapView) findViewById(R.id.mapView);
      map.setStreetView(true);
      map.setSatellite(false);
      map.setClickable(true);
      map.setEnabled(true);
      map.setFocusable(true);
      map.setFocusableInTouchMode(true);
      map.setBuiltInZoomControls(true);
      map.preLoad();
      mapController = map.getController();
      mapController.setZoom(10);
  }
   
  void saveNote(final Location location, final String name, final String note)
  {
      if (location != null ) { 
          Executors.newCachedThreadPool().execute(new Runnable() {
              @Override
              public void run()
              {
                  try {
                	  
                	  	ClientOperations.insertDBNote(name, note, client_id, location);
                	  
                  } catch (Exception e) {
                      Log.e("WEYNAK.user.save_location", e.getMessage());
                  }
              }
          });
      }
  }
    

   public void LocatePosition(double longi, double lati, String name, String link, String date){

	   	mapOverlays = map.getOverlays();
	    Location loc2 = new Location("friend");
	    loc2.setLatitude(lati);
	    loc2.setLongitude(longi); 
	    
	    String friendlocation = WeynakUtils.getAddress(Maps.this, loc2);
	    FriendOverlay itemizedoverlay = new FriendOverlay(this,link,date,loc2);
	    int l1 = (int)(longi * 1E6) ;
	    int l2 = (int)(lati * 1E6) ;
	    GeoPoint point = new GeoPoint(l2,l1);
	    OverlayItem overlayitem = new OverlayItem(point, name, friendlocation);
	    itemizedoverlay.addOverlay(overlayitem);
	    
	    mapOverlays.add(itemizedoverlay);
	    map.postInvalidate();
   }
   
   public void LocateNote(double longi, double lati, String title, String desc, String date, String user){
		
	   	mapOverlays = map.getOverlays();
	    Drawable drawable = getBaseContext().getResources().getDrawable(R.drawable.fav_marker_small);
	    NoteOverlay itemizedoverlay = new NoteOverlay(drawable,this,date,user);
	    int l1 = (int)(longi * 1E6) ;
	    int l2 = (int)(lati * 1E6) ;
	    GeoPoint point = new GeoPoint(l2,l1);
	    OverlayItem overlayitem = new OverlayItem(point, title, desc);
	    overlayitem.setMarker(drawable);
	    itemizedoverlay.addOverlay(overlayitem);
	    
	    mapOverlays.add(itemizedoverlay);
  }
   
   public void LocatePhoto(double longi, double lati, String user, String date, String snap){
		   
	    mapOverlays = map.getOverlays();
		Drawable drawable = getBaseContext().getResources().getDrawable(R.drawable.picture_marker_small);
	    PhotoOverlay itemizedoverlay = new PhotoOverlay(drawable,this,snap);
	    int l1 = (int)(longi * 1E6) ;
	    int l2 = (int)(lati * 1E6) ;
	    GeoPoint point = new GeoPoint(l2,l1);
	    OverlayItem overlayitem = new OverlayItem(point, user , date);
	    overlayitem.setMarker(drawable);
	    itemizedoverlay.addOverlay(overlayitem);
	    mapOverlays.add(itemizedoverlay);
 }
   
  @Override
  protected boolean isRouteDisplayed() {
    return false;
  }
  
  
        
 
  public synchronized void initLocations(final int loadingstatus){
	  
	  Maps.this.runOnUiThread(new Runnable() {
	      public void run() {
	  if(loadstatus==loadingstatus){
		  return;
	  }
	  
	 loadstatus = loadingstatus;
	  
	 switch(loadstatus){
	 case INIT_LOADING:
		 initLocations(MY_NOTES_DONE);
		 break;
	 
	 case MY_NOTES_DONE:
		 if(pref.getBoolean("My saved locations", false)){
			 try {
				mynotes = ClientOperations.getMyNotes(client_id);
				displayMyNotes();
			} catch (Exception e) {
				
			}
		 }
		 initLocations(NOTES_DONE);
		 break;
		 
	 case NOTES_DONE:
		 if(pref.getBoolean("My friends' saved locations", false)){
			 try {
				 notes = ClientOperations.getNotes(client_id);
				 displayNotes();
			} catch (Exception e) {
				
			}
		 }
		 initLocations(MY_PHOTOS_DONE);
		 break;
		 
	 case MY_PHOTOS_DONE:
		 if(pref.getBoolean("My photos", false)){
			 try {
				 myphotos = ClientOperations.getMyPhotos(client_id);
				 displayMyPhotos();
			} catch (Exception e) {
				
			}
		 }
		 initLocations(PHOTOS_DONE);
		 break;
		 
	 case PHOTOS_DONE:
		 if(pref.getBoolean("My friends' photos", false)){
			 try {
				 photos = ClientOperations.getPhotos(client_id);
				 displayPhotos();
			} catch (Exception e) {
				
			}
		 }
		 initLocations(LOCATIONS_DONE);
		 break;
		 
	 case LOCATIONS_DONE:
		 if(pref.getBoolean("My friends' locations", false)){
			 try {
				 friends = ClientOperations.getFriends(client_id);
				 displayFriends();
			} catch (Exception e) {
				
			}
		 }
		 initLocations(LOCATIONS_EMPTY);
		 break;
		 
	 case LOCATIONS_EMPTY:
		 break;
	 }
	      }
	  });

  }
  
	  private void initOverlays()
	  {
	      myLocation = new MyOverlay("My Location", this, map, new OnSaveMyPosition() {
	
	          @Override
	          public void onSave(Location lastFix)
	          {
	        	  pref.edit().putString("LAST_LATITUDE", String.valueOf(lastFix.getLatitude())).commit();
	              pref.edit().putString("LAST_LONGITUDE", String.valueOf(lastFix.getLongitude())).commit();
	          }
	      });
	
	      map.getOverlays().add(myLocation);
	      myLocation.enableMyLocation();
	      myLocation.runOnFirstFix(new Runnable() {
			
			@Override
			public void run() {
				myLocation.centerMe(myLocation.getLastFix());
				
				try {
					initLocations(INIT_LOADING);
					ClientOperations.update(pref.getString("FirstName", "UnknownClient")+ " " +pref.getString("LastName", "UnknownClient") , client_id, Double.valueOf(pref.getString("LAST_LATITUDE", "0")),Double.valueOf(pref.getString("LAST_LONGITUDE", "0")), "1");
				} catch (Exception e) {
					Log.e("WEYNAK.update.on.First.Fix", e.getMessage());
				} 
				
			}
		});
	  }
	  
	  public static Location getMyLocation(){
		  return myLocation.getLastFix();
	  }
	  
	 private void loadUserData(final String id) throws ClientProtocolException, IOException{
		 new Thread() {

			  public void run() {
				  
				  	String name = null, lastname = null,pic_link = null;
				 	java.io.InputStream is = null;
				  
		try{
		 	
		 	List<NameValuePair> parameters = new ArrayList<NameValuePair>();
	        parameters.add(new BasicNameValuePair("uid", id));
		    HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(URI_LINK + USER_DATA);	       
	        httppost.setEntity(new UrlEncodedFormEntity(parameters));
	        HttpResponse response = httpclient.execute(httppost);
	        HttpEntity entity = response.getEntity();
	        is = entity.getContent();
        }
				  catch(Exception e){
		    	        Log.e("WEYNAK.load.user.data", "Error in http connection "+e.toString());
		    	        
		    	}
	        try{
    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    	        StringBuilder sb = new StringBuilder();
    	        String line = null;

    	        while ((line = reader.readLine()) != null) {
    	                sb.append(line + "\n");
    	                
    	        }
    	        is.close();
    	        String result = sb.toString();


    	        JSONArray jArray = new JSONArray(result);
    	        JSONObject json_data = jArray.getJSONObject(0);
    	         
                if(json_data.getString("fname") != null && json_data.getString("lname")!= null && json_data.getString("picture") != null )  
                {	
               		name = json_data.getString("fname");
               		lastname = json_data.getString("lname");
               		pic_link = json_data.getString("picture");
    				pref.edit().putString("FirstName", name).commit();
    				pref.edit().putString("LastName", lastname).commit();
    				
    	        }
                username = name + " " + lastname;
                picture_link = pic_link;
                utils.sendEmptyMessage(PROFILE_PIC);
                    	
    	}catch(JSONException e){
    	        Log.e("WEYNAK", "Error parsing data "+e.toString());
    	} 
    	catch (IOException e) {
			e.printStackTrace();
		}
			  }

		  }.start();
		  
	 }
	 
	 @Override
	protected void onPause() {
		super.onPause();
		myLocation.disableMyLocation();
		Settings.connectToBatteryService(this, false); 
	}
	 @Override
	protected void onResume() {
		super.onResume();
		myLocation.enableMyLocation();
		Settings.connectToBatteryService(this, true);
	}
	 
	 @Override
	public void onBackPressed() {
		return;
	}

//Create menu	
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);

	menu.add(1, 4, 0, "Locate my position").setIcon(android.R.drawable.ic_menu_mylocation);
	menu.add(1, 5, 0, "Close Application").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
	menu.add(1, 2, 0, "Tell-a-friend").setIcon(android.R.drawable.ic_menu_send);
	menu.add(1, 3, 0, "Refresh").setIcon(android.R.drawable.ic_popup_sync);
	menu.add(1, 1, 0, "Settings").setIcon(android.R.drawable.ic_menu_preferences);

return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {  
   case 4: 
	   myLocation.centerMe(false);
	   break;
   case 2: 
	   Location l = myLocation.getLastFix();
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hey there, I'm using Weynak\n");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is my current location :\n " + l.getLatitude() + " , " + l.getLongitude());
		startActivity(Intent.createChooser(sharingIntent,"Share using"));
		
	   break;
   case 3:  
	   if(!mapOverlays.isEmpty())
	   {
		   mapOverlays = map.getOverlays();
		   mapOverlays.clear();
	   }
	   initOverlays();
   	break;
   case 1: 
	   Intent settings = new Intent(Maps.this, Settings.class);
	   startActivityForResult(settings, SETTINGS);
	   break;
   case 5:
	   System.exit(0);
	   break;
}
return false;
}
}